package client

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

/*
 * @Author: Daived
 * @DateTime: 2020/11/29 9:25 上午
 * @Remark: 普通request请求
 */
func HttpRequest(){
	//// Get 无参数
	resp,e := http.Get("http://127.0.0.1:8000/go")
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	// 使用完成后必须关闭回复的主体
	defer resp.Body.Close()
	fmt.Println(resp.Status)

	// Post
	resp,e = http.Post("http://127.0.0.1:8000/go","application/json",strings.NewReader("{\"id\":1}"))
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status)

	// Post From
	resp,e = http.PostForm("http://127.0.0.1:8000/go/demo1",url.Values{"id":{"123"}})
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status)
}

func HttpDo() {
	// 创建客户端
	client := &http.Client{}

	req,e := http.NewRequest(http.MethodPost,"http://127.0.0.1:8000/go",strings.NewReader("{\"id\":20}"))
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	// 设置handler
	req.Header.Set("Content-Type","application/json")

	resp,e := client.Do(req)
	if e != nil {
		fmt.Println(e.Error())
		return
	}
	defer resp.Body.Close()

	fmt.Println(getBodyString(resp.Body))
}

/*
 * @Author: Daived
 * @DateTime: 2020/11/29 9:25 上午
 * @Remark: 获取body
 */
func getBodyString(reader io.Reader) (string,error) {
	body,e := ioutil.ReadAll(reader)
	if e != nil {
		return "", e
	}
	return string(body),nil
}
